#include <QtQml>

#include "utilsprivate.h"
#include "animationBinder.h"


AnimationBinder::AnimationBinder(QObject *parent):BasePropertyBinder(parent)
{

}

AnimationBinder::~AnimationBinder()
{

}

bool isKeyframeGroup(QObject* obj){
    auto meta = obj->metaObject();

    return UtilsPrivate::isBase(QByteArrayLiteral("QQuickKeyframeGroup"),meta);
}

BasePropertyBinder::BindDataList AnimationBinder::generateBindList()
{
    BasePropertyBinder::BindDataList ret;

    auto targetMap = UtilsPrivate::groupById(target());

    auto objs = source()->findChildren<QObject*>();

    for(auto i:objs)
    {
        if(isKeyframeGroup(i))
        {
            QObject* source = i->property("target").value<QObject*>();

            if(!source) continue;
            auto ctx = qmlContext(source);
            if(!ctx) continue;

            auto name = ctx->nameForObject(source);
            if(!targetMap.contains(name)) continue;
            auto target = targetMap[name];

            QString property = i->property("property").toString();

            auto p1 = source->metaObject()->property(source->metaObject()->indexOfProperty(property.toLocal8Bit()));
            auto p2 = target->metaObject()->property(target->metaObject()->indexOfProperty(property.toLocal8Bit()));

            if(!p1.isValid() || !p2.isValid())
            {
                continue;
            }

            BasePropertyBinder::BindData data;

            data.dst = target;
            data.dstProp = p2;
            data.src = source;
            data.srcProp = p1;

            ret << data;
        }
    }

    return ret;
}
